<?php


namespace App\Services;



use App\Exceptions\ApiException;
use App\Models\AdminMenu;

class AdminMenuService
{
    /**
     * 获取管理员的菜单
     * @param int $adminId
     * @param AdminService $adminService
     * @return array
     */
    public function getTreeList(int $adminId, AdminService $adminService)
    {
        $adminRules = $adminService->getRulesByAdminId($adminId);
        $menus = AdminMenu::all('id', 'pid', 'name', 'rule_id')->toArray();
        $list = $this->getAdminMenu($adminRules, $menus);
        return generateTree($list);
    }


    /**
     * 获取某个管理员的菜单
     * @param array $rules 管理员的权限id列表
     * @param array $menus 菜单列表
     * @return array
     */
    private function getAdminMenu(array $rules, array $menus)
    {
        $ruleArr = array_flip($rules);
        $menuArr = array_column($menus, null, 'rule_id');
        $intersect = array_intersect_key($menuArr, $ruleArr);
        return array_column($intersect, null, 'id');
    }


    /**
     * 新增和修改菜单
     * @param array $data
     */
    public function save(array $data)
    {
        $menu = AdminMenu::firstOrNew(['rule_id' => $data['rule_id']]);
        $menu->name = $data['name'];
        $menu->pid = $data['pid'];
        $menu->rule_id = $data['rule_id'];
        $menu->save();
    }


    /**
     * 删除某个菜单
     * @param $id
     */
    public function del($id)
    {
        $admin = AdminMenu::find($id);
        if (empty($admin)){
            throw new ApiException(30001);
        }
        $admin->delete();
    }

}
